/*
 * Created on Jul 19, 2004
 */
package cheme.ProcessEditor.DirectEdit;

import org.eclipse.jface.viewers.ICellEditorValidator;

import cheme.ProcessModel.Interpreter.Parsers.IParser;

/**
 * ICellValidator to validate direct edit values in the column label
 * Collaborates with an instance of ValidationMessageHandler
 * 
 * @author Phil Zoio
 */
public class WritableFieldCellEditorValidator implements ICellEditorValidator
{
	private ValidationMessageHandler handler;
	private IParser parser = null;
	
	/**
	 * @param validationMessageHandler the validation message handler to pass error information to
	 */
	public WritableFieldCellEditorValidator(ValidationMessageHandler validationMessageHandler, IParser parser)
	{
		this.handler = validationMessageHandler;
		this.parser = parser;
	}

	public IParser getParser()
	{
		return parser;
	}

	public void setParser(IParser parser)
	{
		this.parser = parser;
	}

	/**
	 * @param validation of column type
	 * @return the error message if an error has occurred, otherwise null
	 */
	public String isValid(Object value)
	{
		String result = unsetMessageText();
		String string = (String)value;
		
		/*
		 * If the parser is null or the string is null, we take that as the 
		 * content is not invalid so just return null.
		 * 
		 * If there is a parser and content, we test it for potential invalidity.
		 */
				
		if(null != getParser() && null != string)
		{
			if(true != getParser().syntaxIsValid(string))
			{
				result = setMessageText(getParser().getMessage());
			}
		}
		
		return result;
	}

	protected String unsetMessageText()
	{
		handler.reset();
		return null;
	}

	protected String setMessageText(String text)
	{
		handler.setMessageText(text);
		return text;
	}
}
